package tests;

import us.versus.them.isod.SplitDigger;

class SplitDiggerTest extends haxe.unit.TestCase {

	public function testSplitDigger() {
		for ( i in 0 ... 100 ) {
			splitDigginIt();
		}
	}

	public function splitDigginIt() {
		var map = new Array< Array< String > >();
		var w = 78;
		var h = 40;

		w = 512;
		h = 512;

		for ( y in 0 ... h ) {
			var row = new Array< String >();
			map.push( row );
			for ( x in 0 ... w ) {
				row.push( '#' );
			}
		}
		//trace( '\n' );
		var digger = new SplitDigger();
		digger.dig( map );
		//printm( map );

		for ( row in map ) {
			for( i in 0 ... row.length ) {
				if ( '#' != row[ i ] ) {
					row[ i ] = ' ';
				}
			}
		}
		//printm( map );
		var max = 0;
		for ( i in 0 ... 10 ) {
			if ( flood( map, i ) ) {
				max = i;
			}
		}
		if ( 0 != max ) {
			trace( 'WARNING: unconnected sections: ' + ( 1 + max ) );
			printm( map );
		}
		assertEquals( 0, max );
	}

	public function flood( map:Array< Array< String > > , i:Int ) {
		var could = false;
		for ( y in 0 ... map.length ) {
			for ( x in 0 ... map[ y ].length ) {
				if ( ' ' == map[ y ][ x ] ) {
					//trace( 'flood ' + x + ',' + y + ' with ' + i );
					go_flood( map, x, y, i );
					could = true;
				}
				if ( could ) break;
			}
			if ( could ) break;
		}
		return could;
	}

	public function go_flood( map:Array< Array< String > >, x:Int, y:Int, i:Int ) {
		if ( ' ' == map[ y ][ x ] ) {
			map[ y ][ x ] = '' + i;
			go_flood( map, x - 1, y - 1, i );
			go_flood( map, x - 1, y - 0, i );
			go_flood( map, x - 1, y + 1, i );

			go_flood( map, x - 0, y - 1, i );
			go_flood( map, x - 0, y - 0, i );
			go_flood( map, x - 0, y + 1, i );

			go_flood( map, x + 1, y - 1, i );
			go_flood( map, x + 1, y - 0, i );
			go_flood( map, x + 1, y + 1, i );
		}
	}

	public function printm( map:Array< Array< String > > ) {
		trace( '\n' );
		for ( row in map ) {
			var s = '';
			for ( v in row ) {
				s += v;
			}
			trace( s );
		}

	}
}
